package org.example.interceptor;



import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.model.Result;
import org.example.util.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

//定义拦截器
public class AdminTokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入到了拦截器");
          //获得token
         String adminToken  =  request.getHeader("adminToken");
        System.out.println("token:"+adminToken);

         if(JWTUtil.verify(adminToken)){
             return true; //拦截器中返回true, 请求就会离开拦截器,继续向后执行,到达处理器
         }else{
             response.setContentType("text/html;charset=utf-8");
             PrintWriter writer = response.getWriter();
             Result result = new Result(401,"token验证失败",null);
             ObjectMapper mapper = new ObjectMapper();
             String json = mapper.writeValueAsString(result);
             writer.write(json);
             return false;//拦截器中返回false. 不会继续向后执行.  可以在拦截器中向用户做出响应
         }
    }
}
